package com.example.kotlinstudy.习惯用法

import android.os.Build
import androidx.constraintlayout.solver.widgets.Rectangle
import java.io.File
import java.lang.ArithmeticException
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import java.math.BigDecimal
import java.nio.file.Files
import java.nio.file.Paths

//创建DTO
data class Customer(val name: String, val email: String)

//函数的默认参数
fun foo(a: Int = 0, b: String = "") {}

//过滤list
val list = listOf<Int>(0, 2, 3);
val positives = list.filter { x -> x > 0 }
val positives02 = list.filter { it > 0 }
fun main() {
    for (item in positives) {
        print(item)
    }
    println()
    for (item in positives02) {
        print(item)
    }
    println()
    val emailsList = listOf<String>("john@example.com", "john@example.com");
    //检察元素是否存在于集合中
    if ("john@example.com" in emailsList) {
        println("存在")
    }
    //字符串内插
    val name = "name"
    println("Name $name")
    //类型判断
    val tempList = listOf<Any>(0, "2", 3.1);
    for (obj in tempList) {
        when (obj) {
            is Int -> {
                println("$obj is Int")
            }
            is String -> {
                println("$obj is String")
            }
            else -> {
                println("$obj is Any")
            }
        }
    }
    //只读list
    val list = listOf<String>("a", "b", "c")
    //访问map条目
    val map = mutableMapOf("a" to 1, "b" to 2, "c" to 3)
    println(map["a"])
    map["a"] = 2
    println(map["a"])
    //遍历map或者pair型list
    for ((k, v) in map) {
        println("$k -> $v")
    }
    ///区间迭代
    for (i in 1..10) {
        print(i)
    }
    println()
    for (x in 2..10 step 2) {
        print(x)
    }
    println()
    for (x in 10 downTo 1) {
        print(x)
    }
    println()
    (1..10).forEach { a ->
        print(a)
    }
    //延迟属性
//    val p: String by lazy {}
    //扩展函数
    fun String.spaceToCamelCase() {}
    "Convert this to camelcase".spaceToCamelCase()
    //实例化一个抽象类
    val myObject = object : MyAbstractClass() {
        override fun doSomething() {
            print("do something")
        }

        override fun sleep() {
            print("sleep")
        }
    }
    myObject.doSomething()
    //if-not-null缩写
    val files = File("Test").listFiles()
    println(files?.size)
    //if_not-null-else缩写
    val files02 = File("Test").listFiles()
    println(files?.size ?: "empty")
    val fileSize = files?.size ?: run { }
    println(fileSize)
    //if null 执行一个语句
    val values = mutableMapOf("email" to 1)
    val email = values["email"] ?: throw IllegalStateException("Email is missing!")
    //在可能会空的集合中取第一元素
    val emails = listOf<Int>()
    val mainEmail = emails.firstOrNull() ?: ""
    //if not null 执行代码
    var value: Int? = 1;
//    var value: Int? = null;
    value?.let {}
    //映射可空值
    val mapped = value?.let {
        value = transformValue(it)
        println(value)
    } ?: 1
    println(mapped)
    println(transform("Red"))
    println(test())
    //if表达式
    val x = 1;
    val y = if (x == 1) {
        "one"
    } else if (x == 2) {
        "two"
    } else {
        "other"
    }
    println(arrayOfMinusOnes(3))
    ///对一个对象实例调用多个方法（with）
    val myTurtle = Turtle()
    with(myTurtle) {
        penDown()
        for (i in 1..4) {
            forward(100.0)
            turn(90.0)
        }
        penUp()
    }
    ///配置对象的属性（apply）
    val myRectangle = Rectangle().apply {
        var length = 4
        var breadth = 5
        var color = 0xFAFAFA
    }
    ///java 7 的try-with-resource
    val stream = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        Files.newInputStream(Paths.get("/some/file.txt"))
    } else {
        TODO("VERSION.SDK_INT < O")
    }
    stream.buffered().reader().use { reader ->
        println(reader.readText())
    }
    ///可空布尔值
    val b: Boolean? = true
    if (b == true) else {
    }
    ///交换两个变量
    var a1 = 1
    var b1 = 2
    a1 = b1.also { b1 = a1 }
    fun calcTaxes(): BigDecimal = TODO("Waiting for feedback from accounting")
}

//单表达式函数
fun theAnswer() = 42
fun theAnswer002(): Int {
    return 42
}

//单表达式函数
fun transform002(color: String): Int = when (color) {
    "Red" -> 0
    "Green" -> 1
    "Blue" -> 2
    else -> throw IllegalStateException("error")
}

//返回类型为Unit的方法的构建器风格用法
fun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}

//try-catch
fun test() {
    val result = try {
        println("try something")
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }
}

//返回when表达式
fun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}

fun transformValue(a: Int): Int {
    return 0
}

//创建单例
object Resource {
    val name = "Name"
}

//抽象类
abstract class MyAbstractClass {
    abstract fun doSomething()
    abstract fun sleep()
}

class Turtle {
    fun penDown() {}
    fun penUp() {}
    fun turn(degrees: Double) {}
    fun forward(pixels: Double) {}
}

//inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)